import { Directive, OnInit, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import dayjs from 'dayjs';
import { switchMap } from 'rxjs/operators';

@Directive({
	selector: '[mTimeFormControl]',
	providers: [
		{
			multi: true,
			provide: NG_VALUE_ACCESSOR,
			useExisting: TimeFormControlDirective,
		},
	],
})
export class TimeFormControlDirective implements ControlValueAccessor {
	constructor(private elRef: ElementRef<HTMLInputElement>) {}

	writeValue(obj: Date): void {
		const date = dayjs(obj);
		if (!date.isValid) {
			this.elRef.nativeElement.value = '';
			return;
		}
		// valueAsDate忽略时区，手动增加时区偏移
		this.elRef.nativeElement.valueAsDate = date
			.add(-obj.getTimezoneOffset(), 'minute')
			.second(0)
			.millisecond(0)
			.toDate();
	}
	registerOnChange(fn: any): void {
		this.elRef.nativeElement.addEventListener('change', () => {
			const date = this.elRef.nativeElement.valueAsDate;
			if (!date) {
				fn(null);
				return;
			}
			// 矫正时区偏移
			const value = dayjs(date)
				.add(date.getTimezoneOffset(), 'minute')
				.toDate();
			fn(value);
		});
	}
	registerOnTouched(fn: any): void {
		this.elRef.nativeElement.addEventListener('touchend', fn);
	}
	setDisabledState?(isDisabled: boolean): void {
		this.elRef.nativeElement.disabled = isDisabled;
	}
}
